//
//  TLConvertWavToMp3.m
//  KidReading
//
//  Created by telen on 2017/5/5.
//  Copyright © 2017年 刘赞黄Telen. All rights reserved.
//

#import "TLConvertWavToMp3.h"
#import "lame.h"

#define CV_buffer_p  8192 //最小无损数据单元

@implementation TLConvertWavToMp3

+ (BOOL)ConvertWavFile:(NSString *)wavFilePath toMp3File:(NSString *)mp3Path progress:(void (^)(float, unsigned long long))progress
{
    if (wavFilePath.length <= 0 || mp3Path.length <= 0 || ![[NSFileManager defaultManager] fileExistsAtPath:wavFilePath]) {
        return NO;
    }
    //
    [[NSFileManager defaultManager] removeItemAtPath:mp3Path error:nil];
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:mp3Path]) {
        [[NSFileManager defaultManager] createFileAtPath:mp3Path contents:nil attributes:nil];
    }
    //
    NSFileHandle* handle = [NSFileHandle fileHandleForWritingAtPath:mp3Path];
    
    const char* cwav = [wavFilePath cStringUsingEncoding:NSUTF8StringEncoding];
    //const char* cmp3 = [mp3Path cStringUsingEncoding:NSUTF8StringEncoding];

    //打开 wav文件
    FILE* fwav = fopen(cwav,"rb");
    //FILE* fmp3 = fopen(cmp3,"wb");
    
    //计算wav 大小
    NSFileHandle* readle = [NSFileHandle fileHandleForWritingAtPath:wavFilePath];
    unsigned long long allsize = [readle seekToEndOfFile];
    [readle closeFile];
    
    short int wav_buffer[CV_buffer_p*2];
    unsigned char mp3_buffer[CV_buffer_p];
    
    //1.初始化lame的编码器
    lame_t lame =  lame_init();
    //2. 设置lame mp3编码的采样率
    lame_set_in_samplerate(lame , 44100);
    lame_set_num_channels(lame,2);
    // 3. 设置MP3的编码方式
    lame_set_VBR(lame, vbr_default);
    lame_set_VBR_q(lame, 9);//设置最低质量
    lame_init_params(lame);
    //
    size_t read ; size_t write; //代表读了多少个次 和写了多少次
    unsigned long long total=0; // 当前读的wav文件的byte数目
    //
    read = fread(wav_buffer,sizeof(short int)*2, 12,fwav);//修复mp3起始的脉冲声音(万康语速处理文件)
    do{
        @autoreleasepool {
            read = fread(wav_buffer,sizeof(short int)*2, CV_buffer_p,fwav);
            //
            if(read!=0){
                write = lame_encode_buffer_interleaved(lame,wav_buffer,(int)read,mp3_buffer,CV_buffer_p);
                //把转化后的mp3数据写到文件里
                //fwrite(mp3_buffer,sizeof(unsigned char),write,fmp3);
                [handle seekToEndOfFile];
                [handle writeData:[NSData dataWithBytes:mp3_buffer length:write]];
                //
                //完成进度
                if (progress) {
                    total +=  read* sizeof(short int)*2;
                    progress(1.0*total/allsize,allsize);
                }
            }
            if(read==0){
                lame_encode_flush(lame,mp3_buffer,CV_buffer_p);

                //MP3 info  末尾128字节
                /*0 char 3 "TAG "
                3 char 30 title
                33 char 30 artist
                63 char 30 album
                93 char 4 year
                97 char 30 comments
                127 byte 1 genre */
                //char chr[128] = {""};
                //[handle writeData:[NSData dataWithBytes:chr length:128]];
            }
        }
    }while(read!=0);
    
    lame_close(lame);
    fclose(fwav);
    //fclose(fmp3);
    
    [handle closeFile];
    return YES;
}

@end
